import path from 'node:path'
import process from 'node:process'
import { loadEnv } from 'vite'
import type { ConfigEnv, UserConfig } from 'vite'
import { createVitePlugins } from './build/vite'
import { exclude, include } from './build/vite/optimize'
import Components from 'unplugin-vue-components/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'

// 动态基础路径映射表（项目名 → 路径前缀）
const PROJECT_PATH_MAP: Record<string, string> = {
  kkkk: '/', // 主项目使用根路径
  yyyy: '/',
  dddd: '/',
}

export default ({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)

  // 动态设置基础路径（通过环境变量指定项目ID）
  const projectId = env.VITE_APP_PROJECT_ID || 'kkkk'
  const basePath = PROJECT_PATH_MAP[projectId] || './'

  return {
    // 核心修改：根据项目ID动态设置基础路径 [5,8](@ref)
    base: basePath,

    plugins: [
      ...createVitePlugins(mode),
      Components({
        resolvers: [NaiveUiResolver()],
        dts: 'src/types/naive-ui-components.d.ts',
      }),
    ],

    server: {
      open: true,
      port: 2112,
      proxy: {
        '/dragon': {
          target: 'http://localhost:8888/',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/dragon/, ''),
        },
      },
    },

    resolve: {
      alias: {
        '@': path.join(__dirname, './src'),
        '~': path.join(__dirname, './src/assets'),
        '~root': path.join(__dirname, '.'),
        '@utils': path.join(__dirname, './src/utils'),
      },
    },

    build: {
      cssCodeSplit: false,
      chunkSizeWarningLimit: 2048,
      // 输出目录添加项目标识 [5](@ref)
      outDir: env.VITE_APP_OUT_DIR || `dist-${projectId}`,
      // 启用更彻底的路径处理
      assetsInlineLimit: 4096,
    },

    optimizeDeps: { include, exclude },
  }
}
